package com.chenfan.ccp.plug.log.handler;

import com.chenfan.ccp.handler.BaseHttpResponse;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 修改返回统一结果
 */

public class ResponseParameterInterceptor extends HttpServletResponseWrapper implements BaseHttpResponse {

    private final ByteArrayOutputStream output;
    private ServletOutputStream filterOutput;
    private byte[] errorByte;


    public ResponseParameterInterceptor(HttpServletResponse response) throws IOException {
        super(response);
        output = new ByteArrayOutputStream();
    }

    @Override
    public void setHeader(String name, String value) {
        super.setHeader(name, value);
    }

    @Override
    public String getHeader(String name) {
        return super.getHeader(name);
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        if (filterOutput == null) {
//            filterOutput = new ServletOutputStream() {
//
//                private TeeOutputStream teeOutputStream = new TeeOutputStream(ResponseParameterInterceptor.super.getOutputStream(), output);
//
//                @Override
//                public boolean isReady() {
//                    return false;
//                }
//
//                @Override
//                public void setWriteListener(WriteListener writeListener) {
//
//                }
//
//                @Override
//                public void write(int b) throws IOException {
//                    teeOutputStream.write(b);
//                }
//
//                @Override
//                public void write(byte[] b) throws IOException {
//                    teeOutputStream.write(b);
//                }
//
//                @Override
//                public void write(byte[] b, int off, int len) throws IOException {
//                    teeOutputStream.write(b, off, len);
//                }
//            };
            filterOutput = super.getOutputStream();
        }


        return filterOutput;
    }

    public void setErrorByte(byte[] errorByte) {
        this.errorByte = errorByte;
    }

    public byte[] toByteArray() {
        return errorByte != null ? errorByte : output.toByteArray();
    }
}
